package com.leyou.cart.service;

import com.fasterxml.jackson.core.type.TypeReference;
import com.leyou.auth.entiy.UserInfo;
import com.leyou.cart.client.GoodsClient;

import com.leyou.cart.filter.LoginInterceptor;
import com.leyou.cart.pojo.Cart;
import com.leyou.common.utils.JsonUtils;
import com.leyou.item.api.GoodsApi;
import com.leyou.item.pojo.Sku;
import jdk.nashorn.internal.parser.Parser;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

@Log4j2
@Service
public class CartService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private GoodsClient goodsClient;

    static final String KEY_PREFIX = "ly:cart:uid:";

    /**
     * 添加购物车
     *
     * @param cart
     * @return
     */
    public Boolean addCart(Cart cart) {//。双层map
        try {
            //加入购物车；通过userId获取用户购物车列表；判断商品是否存在，存在商品数量加一。不存在新加入商品
            //通过前置拦截获取用户信息
            UserInfo loginUser = LoginInterceptor.getLoginUser();

            //从redis中；获取购物车列表商品
            BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(KEY_PREFIX + loginUser.getId());
            String skuId = cart.getSkuId().toString();
            Integer cartNum = cart.getNum();
            if (operations.hasKey(skuId)) {//存在商品数量加一
                String oldCart = operations.get(skuId).toString();
                Cart cart1 = JsonUtils.parse(oldCart, Cart.class);
                cart1.setNum(cart1.getNum() + cartNum);

                operations.put(skuId, JsonUtils.serialize(cart1));

            } else {//商品不存在，添加商品
                //查询商品，并添加
                Sku sku = this.goodsClient.querySkuBySkuId(cart.getSkuId());
                if (sku == null) {
                    log.error("添加购物车商品不存在：skuId:{}", skuId);
                    throw new RuntimeException();
                }
                cart.setImage(StringUtils.isBlank(sku.getImages()) ? "" :
                        StringUtils.substringBefore(sku.getImages(), ","));
                cart.setPrice(sku.getPrice());
                cart.setTitle(sku.getTitle());
                cart.setUserId(loginUser.getId());
                cart.setOwnSpec(sku.getOwnSpec());
                operations.put(skuId, JsonUtils.serialize(cart));//转化为json数据存进去redis
            }
            return true;
        } catch (RuntimeException e) {
            e.printStackTrace();
            log.error("添加购物车失败");
            return false;
        }
    }

    /**
     * 登入查询购物车，redis中查询购物车
     *
     * @return
     */
    public List<Cart> queryCart() {
        UserInfo loginUser = LoginInterceptor.getLoginUser();
        /*//判断是否有购物车数据,没有数据结束
        if(!redisTemplate.hasKey(loginUser.getId()+KEY_PREFIX)){
            return null;
        }*/

        BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(KEY_PREFIX + loginUser.getId());
        //双层map，判断购物车数据是否存在。。得到第二层map获取value
        List<Object> carts = ops.values();//获取map中的values;


        List<Cart> cartList = new ArrayList<>();
        if (null != carts) {//carts不为空；组合carts返回。。由于carts是字符串类型的对象，转换json类型存储
            carts.forEach(cart -> {
                cartList.add(JsonUtils.nativeRead(cart.toString(), new TypeReference<Cart>() {
                }));
            });
        }
        return cartList;
    }



    /**
     * 删除商品在redis
     * @param skuId
     */
    public void deleteCart(Long skuId) {
        //先找对对应的商品列表，在对应商品列表，然后删除
        UserInfo loginUser = LoginInterceptor.getLoginUser();
        BoundHashOperations<String, Object, Object> ops = this.redisTemplate.boundHashOps(KEY_PREFIX + loginUser.getId());
        ops.delete(skuId.toString());//直接删除指定的商品id

    }

    /**
     * 增加购物车商品数量
     * @param cart
     */
    public void updateIncrementCart(Cart cart) {
        //先查出redis中对应的商品信息
        //获取用户信息
        UserInfo loginUser = LoginInterceptor.getLoginUser();
        //根据用户id获取购物车的商品信息
        BoundHashOperations<String, Object, Object> ops = this.redisTemplate.boundHashOps(KEY_PREFIX + loginUser.getId());
        //根据商品的id获取商品信息
        String oldCart = ops.get(cart.getSkuId().toString()).toString();
        Cart cartRedis = JsonUtils.parse(oldCart, Cart.class);
        cartRedis.setNum(cartRedis.getNum()+1);//修改商品数量
        //修改完之后保存到redis中////JsonUtils.serialize 只是把cart对象转为json
        ops.put(cart.getSkuId().toString(),JsonUtils.serialize(cartRedis));
    }
}
